/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.work.day.web;
import com.google.common.collect.Lists;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.work.day.entity.WordBean;
import com.jeeplus.modules.work.day.entity.WorkDay;
import com.jeeplus.modules.work.day.service.WorkDayService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 工作日配置Controller
 * @author azj
 * @version 2020-04-24
 */
@RestController
@RequestMapping(value = "/work/day/workDay")
public class WorkDayController extends BaseController {
	@Autowired
	private WorkDayService workDayService;

	@ModelAttribute
	public WorkDay get(@RequestParam(required=false) String id) {
		WorkDay entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workDayService.get(id);
		}
		if (entity == null){
			entity = new WorkDay();
		}
		return entity;
	}

	/**
	 * 保存配置成功列表数据
	 */
	@RequiresPermissions("work:day:workDay:list")
	@GetMapping("list")
	public AjaxJson list(WorkDay workDay, HttpServletRequest request, HttpServletResponse response) {
		Map<String,Object> map=new HashMap<>();
		map.put("curPage",request.getParameter("pageNo"));
		map.put("pageSize",request.getParameter("pageSize"));
		map.put("beginWorkTime",workDay.getBeginWorkTime());
		map.put("endWorkTime",workDay.getEndWorkTime());
		WordBean<WorkDay> page = workDayService.findListValue(map);
		return AjaxJson.success().put("page",page);
	}



	/**
	 * 根据Id获取保存配置成功数据
	 */
	@RequiresPermissions(value={"work:day:workDay:view","work:day:workDay:add","work:day:workDay:edit"},logical=Logical.OR)
	@GetMapping("queryById")
	public AjaxJson queryById(WorkDay workDay) {
		return AjaxJson.success().put("workDay", workDay);
	}

	/**
	 * 保存保存配置成功
	 */
	@RequiresPermissions(value={"work:day:workDay:add","work:day:workDay:edit"},logical=Logical.OR)
	@PostMapping("save")
	public AjaxJson save(WorkDay workDay, Model model) throws Exception{
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(workDay);
		if (StringUtils.isNotBlank(errMsg)){
			return AjaxJson.error(errMsg);
		}
		//新增或编辑表单保存
		workDayService.save(workDay);//保存
		return AjaxJson.success("保存配置成功");
	}


	/**
	 * 批量删除保存配置成功
	 */
	@RequiresPermissions("work:day:workDay:del")
	@DeleteMapping("delete")
	public AjaxJson delete(String ids) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workDayService.delete(workDayService.get(id));
		}
		return AjaxJson.success("删除配置成功");
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("work:day:workDay:export")
    @GetMapping("export")
    public AjaxJson exportFile(WorkDay workDay, HttpServletRequest request, HttpServletResponse response) {
		try {
            String fileName = "保存配置成功"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkDay> page = workDayService.findPage(new Page<WorkDay>(request, response, -1), workDay);
    		new ExportExcel("保存配置成功", WorkDay.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error("导出保存配置成功记录失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("work:day:workDay:import")
    @PostMapping("import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<WorkDay> list = ei.getDataList(WorkDay.class);
			for (WorkDay workDay : list){
				try{
					workDayService.save(workDay);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条保存配置成功记录。");
			}
			return AjaxJson.success( "已成功导入 "+successNum+" 条保存配置成功记录"+failureMsg);
		} catch (Exception e) {
			return AjaxJson.error("导入保存配置成功失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 下载导入保存配置成功数据模板
	 */
	@RequiresPermissions("work:day:workDay:import")
    @GetMapping("import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		try {
            String fileName = "保存配置成功数据导入模板.xlsx";
    		List<WorkDay> list = Lists.newArrayList();
    		new ExportExcel("保存配置成功数据", WorkDay.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error( "导入模板下载失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 工作日列表数据
	 */
	@RequiresPermissions("work:day:workDay:findListDate")
	@GetMapping("findListDate")
	public AjaxJson findListDate(HttpServletRequest request, HttpServletResponse response) {

		SimpleDateFormat sdf=new SimpleDateFormat("YYYY");
		int data = Integer.valueOf(sdf.format(new Date()));
		List<Integer>  list=workDayService.findListDate(data,data+10);
		if(list == null || list.size() == 0){
           list.add(data);
           return AjaxJson.success().put("data",list).put("total",0);
		}else{
			return AjaxJson.success().put("data",list).put("total",list.size());
		}

	}

	/**
	 * 保存工作日配置
	 */
	@RequiresPermissions(value={"work:day:workDay:saveDate"},logical=Logical.OR)
	@PostMapping("saveDate")
	public AjaxJson saveDate(String dates, Model model, HttpServletRequest request ,Object hanlder) throws Exception{
		/**
		 * 后台hibernate-validation插件校验
		 */
		List<WorkDay> work=new ArrayList<WorkDay>();
		/**
		 * 获取初始化日期
		 */
		if(StringUtils.isNotBlank(dates)){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar calendar = Calendar.getInstance();
			Date date=null;
			String[] split=dates.split(",");
			for(int k=0;k<split.length;k++){
				try {
					date = sdf.parse((split[k]+"-01-01"));
				} catch (ParseException e){
					return AjaxJson.success("保存配置失败");
				}
				String lastDay="";
				/**
				 * 循环初始化日期
				 */
				int i=0;
				while(true){
					WorkDay works=new WorkDay();
					calendar.setTime(date);
					int day=calendar.get(Calendar.DATE);
					// 后一天为 +1   前一天 为-1
					calendar.set(Calendar.DATE,day+i);
					if(calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY){
						works.setWorkStatus("1");
					} else{
						works.setWorkStatus("0");
					}
					lastDay = sdf.format(calendar.getTime());
					/**
					 * 下一年跳出循环
					 */
					if(! split[k].equals(lastDay.substring(0,4))){
						works=null;
						break;
					}
					works.setWorkTime(lastDay);
					works.setCreateDate(new Date());
					works.setCreateBy(UserUtils.getUser());
					date=calendar.getTime();
					i=1;
					work.add(works);
					works=null;
				}

				/**
				 * 批量添加
				 */
				try{
					workDayService.saveList(work);
					work.clear();
				}catch(Exception e){
					return AjaxJson.success("保存配置失败");
				}
			}
		}
		return AjaxJson.success("保存配置成功");
	}

}

